package com.yorick.authority.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yorick.authority.entitys.BaseListDto;
import com.yorick.authority.entitys.DepartmentDto;
import com.yorick.authority.entitys.Node;
import com.yorick.authority.modal.request.department.*;
import com.yorick.authority.modal.response.BaseListResponse;
import com.yorick.authority.modal.response.department.DepartmentResponse;
import com.yorick.authority.service.AbstractAuthorityService;
import com.yorick.authority.service.DepartmentService;
import com.yorick.common.Result.SimpleFactory.ResultFactory;
import com.yorick.common.error.YorickException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.yorick.authority.util.Util.sparatePage;

@Service
public class DepartmentServiceImpl extends AbstractAuthorityService implements DepartmentService {

    @Override
    public Map<String, Object> addDepartment(DepartmentAddRequest request) throws YorickException {
        //添加机构
        DepartmentDto departmentDto = DepartmentDto.builder()
                .dname(request.getDname())
                .description(request.getDescription())
                .parentId(request.getParentId())
                .build();
        try {
            departmentMapper.insertDepart(departmentDto);
        }catch (DuplicateKeyException ex){
            throw new YorickException("0", "该机构已存在");
        }
        return ResultFactory.success().display();
    }

    @Override
    public BaseListResponse departmentList(DepartmentListRequest request) {
        Integer currentPage = request.getCurrentPage();
        Integer pageSize = request.getPageSize();
        Integer start = (currentPage - 1) * pageSize;

        BaseListDto data = BaseListDto.builder()
                .keyword(request.getKeyword())
                .superRole(request.isSuperRole())
                .dids(getDID(request.getAid()))
                .build();

        List<DepartmentDto> departments = departmentMapper.findDepartmentList(data);
        List<JSONObject> departmentsTree = new ArrayList<>();
        if (departments.size() > 0) {
            departmentsTree = formatTreeRecursionData(departments);
        }
        BaseListResponse response = BaseListResponse.builder()
                .list(sparatePage(departmentsTree, start, pageSize))
                .total(departmentsTree.size())
                .build();
        return response;
    }

    @Override
    public Map<String, Object> editDepartment(DepartmentEditRequest request) {
        //修改主机构
        DepartmentDto departmentDto = DepartmentDto.builder()
                .did(request.getDid())
                .dname(request.getDname())
                .description(request.getDescription())
                .enabled(request.getEnabled())
                .build();
        try {
            departmentMapper.updateDepartment(departmentDto);
        }catch (DuplicateKeyException ex){
            throw new YorickException("0", "该机构已存在");
        }
        return ResultFactory.success().display();
    }

    @Override
    public JSONObject departmentDetail(DepartmentDetailRequest request) {
        List<Integer> dids = departmentMapper.findChildrenByDID(request.getDid());
        List<DepartmentDto> departments = departmentMapper.findDepartmentByDID(dids);
        List<JSONObject> departmentsTree = formatTreeRecursionData(departments);
        return departmentsTree.get(0);
    }

    @Override
    public Map<String, Object> deleteDepartment(DepartmentDeleteRequest request) {
        List<Integer> dids = departmentMapper.findChildrenByDID(request.getDid());
        departmentMapper.deleteDepartmentByDID(dids);
        return ResultFactory.success().display();
    }

    private List<JSONObject> formatTreeRecursionData(List<DepartmentDto> departments){
        int nodeId = departments.get(0).getParentId();
        Map<Integer, Node> nodes = new HashMap<>();
        for (int i = 0; i < departments.size(); i++) {
            DepartmentDto departmentDto = departments.get(i);
            //模拟数据库存储树结构
            Node node = Node.builder()
                    .id(departmentDto.getDid())
                    .parentId(departmentDto.getParentId())
                    .name(departmentDto.getDname())
                    .desc(departmentDto.getDescription())
                    .enabled(departmentDto.getEnabled())
                    .opTime(departmentDto.getOpTime())
                    .build();
            nodes.put(departmentDto.getDid(), node);
        }
        return getNodeJson(nodes);
    }
    @Override
    protected JSONObject customizeNode(Node node) {
        DepartmentResponse childResponse = DepartmentResponse.builder()
                .did(node.getId())
                .dname(node.getName())
                .description(node.getDesc())
                .enabled(node.getEnabled())
                .opTime(node.getOpTime())
                .build();
        return objectMapper.convertValue(childResponse, JSONObject.class);
    }
}
